package com.woyou.component;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.view.KeyEvent;
import android.widget.DatePicker;
import android.widget.TextView;

public class SuperDatePicker {
	private Context context;
	private DatePickerDialog datePickerDialog;
	private TextView time_view;
	// 起始时间
	public int year_time;
	public int month_time;
	public int day_time;
	public String defaultTime;
	
	public SuperDatePicker(Context context, TextView time_view) {
		this.context = context;
		this.time_view = time_view;
		defaultTime=time_view.getText().toString();
		Calendar calendar = Calendar.getInstance();
		year_time = calendar.get(Calendar.YEAR);
		month_time = calendar.get(Calendar.MONTH);
		day_time = calendar.get(Calendar.DAY_OF_MONTH);
		ShowDatePicker();
	}

	public void ShowDatePicker() {
		DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
				day_time = dayOfMonth;
				month_time = monthOfYear;
				year_time = year;
				updateStartDateDisplay(true);
			}
		};
		datePickerDialog=new DatePickerDialog(context, dateSetListener, year_time, month_time,day_time);
		datePickerDialog.setCancelable(false);
		datePickerDialog.setCanceledOnTouchOutside(false);
		datePickerDialog.show();
		datePickerDialog.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				datePickerDialog.cancel();
				updateStartDateDisplay(false);
				return false;
			}
		});
	}

	private void updateStartDateDisplay(boolean isSet) {
		String year=""+year_time;
		String month=null;
		String day=null;
		
		if(month_time>=0&&month_time<=8){
			month="0"+(month_time+1);
		}else{
			month=""+(month_time+1);
		}
		if(day_time>=0&&day_time<=9){
			day="0"+day_time;
		}else{
			day=""+day_time;
		}
		if(isSet){
			time_view.setText(new StringBuilder().append(year).append(".").append(month).append(".").append(day));
		}else{
			time_view.setText(defaultTime);
		}

	}

}
